import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:pplive/common/api_service.dart';
import '../../common/utils.dart';
import '../../routes/AppRoute.dart';
import '../../views/square_cell.dart';
import '../moment_model.dart';
import '../user.dart';

extension MomentExtension on Moment {
  Widget createView([int index = 0, Function(Moment model)? clickBlock]) {
    return SquareCell(
      index: index,
      model: this,
      clickBlock: clickBlock,
    );
  }

  Widget userView(Function() reloadDataBlock) {
    var theme = Util.shared().theme!;
    var user = userInfo ?? User.fromJson({});

    var followColor = const Color(0xFFFE42FF);

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Container(
          width: 46,
          height: 46,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(23),
            image: DecorationImage(
              image: NetworkImage(user.head),
              fit: BoxFit.cover,
            ),
          ),
        ),
        const SizedBox(
          width: 11,
        ),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                user.name,
                style: theme.textTheme.labelLarge,
              ),
              const Text("这是勋章"),
            ],
          ),
        ),
        SizedBox(
            // width: 73,
            height: 25,
            child: OutlinedButton(
                onPressed: () {
                  var onoff = !focusOn;
                  Util.showLoading();
                  // 在这里调用 requestWithCallback 方法
                  ApiService.requestWithCallback(
                    true, // 假设这是一个 GET 请求
                    '/pr/follow', // 替换为实际的 API 路径
                    params: {
                      "onoff": onoff,
                      "tid": userInfo?.uid ?? 0,
                    },
                    debuglog: true,
                    callback: (data) {
                      Util.dimissLoading();
                      if (data.code == ApiCodeSucc) {
                        focusOn = onoff;
                        reloadDataBlock();
                      }
                    },
                  );
                },
                style: ButtonStyle(
                    shape: WidgetStateProperty.all<RoundedRectangleBorder>(
                        RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8))),
                    side: WidgetStateProperty.all<BorderSide>(
                        BorderSide(color: followColor, width: 1))),
                child: Text(
                  focusOn ? "取消关注" : "关注",
                  style: TextStyle(
                    fontFamily: "PingFang SC",
                    fontSize: 12,
                    fontWeight: FontWeight.w500,
                    color: followColor,
                  ),
                ))),
      ],
    );
  }

  Widget picWidget() {
    if (picUrls.isEmpty) {
      return const SizedBox.shrink();
    }

    const int padding = 13;
    const crossAxisSpacing = 10.0;
    const mainAxisSpacing = 10.0;
    var crossAxisCount = 3;
    var pContainerW = Util.SCREENWIDTH() - padding * 2;
    var pContainerH = pContainerW * 3;
    var count = picUrls.length;
    if (count == 1) {
      crossAxisCount = 1;
      pContainerW = 208;
      pContainerH = 208;
    }
    // 少于等于 4 张
    else if (count < 5) {
      crossAxisCount = 2;
      pContainerW = (Util.SCREENWIDTH() - padding * 2) * 0.75;
      pContainerH = (pContainerW - crossAxisSpacing) + mainAxisSpacing;
    } else if (count < 7) {
      crossAxisCount = 3;
      pContainerW = Util.SCREENWIDTH() - padding * 2;
      pContainerH =
          (pContainerW - crossAxisSpacing * 2) / 3 * 2 + mainAxisSpacing;
    }
    // 其他
    else {
      crossAxisCount = 3;
      pContainerW = Util.SCREENWIDTH() - padding * 2;
      pContainerH = (pContainerW - crossAxisSpacing * 2) + mainAxisSpacing * 2;
    }

    return SizedBox(
      width: pContainerW,
      height: pContainerH,
      child: GridView.builder(
        physics: const NeverScrollableScrollPhysics(),
        itemCount: count,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: crossAxisCount,
          crossAxisSpacing: crossAxisSpacing,
          mainAxisSpacing: mainAxisSpacing,
        ),
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
              onTap: () {
                AppPage.photo.go(this);
              },
              child: ClipRRect(
                  borderRadius: const BorderRadius.all(Radius.circular(8.0)),
                  child: CachedNetworkImage(
                    imageUrl: picUrls[index],
                    placeholder: (c, url) => const Icon(Icons.account_circle),
                    errorWidget: (c, url, error) => const Icon(Icons.error),
                    fit: BoxFit.cover,
                  )));
        },
      ),
    );
  }
}

extension ListMomentExtensions on List<Moment> {
  Widget createView(Future<void> Function() onRefresh, ScrollController controller) {
    if (isEmpty) {
      return const Center(child: CircularProgressIndicator());
    }

    return RefreshIndicator(
        onRefresh: onRefresh,
        child: ListView.separated(
          controller: controller,
          itemCount: length,
          itemBuilder: (itemBuilder, index) {
            return this[index]
                .createView(index, (model) => AppPage.squareSub.go(model));
          },
          separatorBuilder: (BuildContext context, int index) {
            return const Divider(
              color: Color(0x14ffffff),
              height: 1,
            );
          },
        ));
  }
}
